package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FillerhazardRestController")
public class FillerhazardRestController extends CmiEmaController {

	/**
	 * Create a new Fillerhazard entity
	 * 
	 */
	@RequestMapping(value = "/newFillerhazard", method = RequestMethod.POST)
	@ResponseBody
	public Object newFillerhazard(@RequestBody Fillerhazard fillerhazard) {
		fillerhazardService.saveFillerhazard(fillerhazard);
		return JSONObject
				.parse(cmiPsonService.toJsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazard.getId()), 2));
	}

	@RequestMapping(value = "/restNewFillerhazard", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFillerhazard(@RequestBody String fillerhazardJson) {
		Fillerhazard fillerhazard = new Gson().fromJson(fillerhazardJson, Fillerhazard.class);
		appendReferences(fillerhazard);
		fillerhazardService.saveFillerhazard(fillerhazard);
		return JSONObject
				.parse(cmiPsonService.toJsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazard.getId()), 2));
	}

	@RequestMapping(value = "/saveFillerhazard", method = RequestMethod.PUT)
	@ResponseBody
	public Fillerhazard saveFillerhazard(@RequestBody Fillerhazard fillerhazard) {
		fillerhazardService.saveFillerhazard(fillerhazard);
		return fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazard.getId());
	}

	@RequestMapping(value = "/restSaveFillerhazard", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFillerhazard(@RequestBody String fillerhazardJson) {
		Fillerhazard fillerhazard = new Gson().fromJson(fillerhazardJson, Fillerhazard.class);
		appendReferences(fillerhazard);
		CmiPsonService cmiPsonService = new CmiPsonService();
		fillerhazardService.saveFillerhazard(fillerhazard);
		return JSONObject
				.parse(cmiPsonService.toJsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazard.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFillerhazard/{fillerhazardId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFillerhazard(@PathVariable Integer fillerhazardId) {
		Fillerhazard fillerhazard = fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId);
		fillerhazardService.deleteFillerhazard(fillerhazard);
	}

	@RequestMapping(value = "/restConfirmDeleteFillerhazards")
	@ResponseBody
	public Object restConfirmDeleteFillerhazards(@RequestBody Set<Integer> deleteFillerhazardsIds) {
		Set<Fillerhazard> deleteFillerhazards = fillerhazardDAO.findFillerhazardsByIds(deleteFillerhazardsIds);
		Set<Fillerhazard> referencedFillerhazards = fillerhazardService.loadReferenceFillerhazards(deleteFillerhazards);
		deleteFillerhazards.removeAll(referencedFillerhazards);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFillerhazards);
		jsonObject.put("deleteEntitys", deleteFillerhazards);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFillerhazards")
	@ResponseBody
	public Object restDeleteFillerhazards(@RequestBody Set<Fillerhazard> deleteFillerhazards) {
		Iterator<Fillerhazard> iterator = deleteFillerhazards.iterator();
		while (iterator.hasNext()) {
			Fillerhazard currentFillerhazard = iterator.next();
			fillerhazardService.deleteFillerhazard(currentFillerhazard);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFillerhazards");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFillerhazard/{fillerhazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerhazard(@PathVariable Integer fillerhazardId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerhazardFiller/{fillerhazardId}/filler", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerhazardFiller(@PathVariable Integer fillerhazardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId).getFiller(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerhazardHazard/{fillerhazardId}/hazard", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerhazardHazard(@PathVariable Integer fillerhazardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId).getHazard(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	public void appendReferences(Fillerhazard fillerhazard) {

		Filler filler = fillerhazard.getFiller();
		if (filler != null)
			fillerhazard.setFiller(fillerService.findFillerByPrimaryKey(filler.getId()));

		Hazard hazard = fillerhazard.getHazard();
		if (hazard != null)
			fillerhazard.setHazard(hazardService.findHazardByPrimaryKey(hazard.getId()));

	}

	@RequestMapping(value = "/restGetFillerhazardFiller/{fillerhazardId}/filler", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerhazardFiller(@PathVariable Integer fillerhazardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId).getFiller(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFillerhazardHazard/{fillerhazardId}/hazard", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerhazardHazard(@PathVariable Integer fillerhazardId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerhazardDAO.findFillerhazardByPrimaryKey(fillerhazardId).getHazard(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFillerhazards", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFillerhazards() {
		return JSONObject.parse(cmiPsonService.toJsonString(fillerhazardService.loadFillerhazards(), 2));
	}

	@RequestMapping(value = "/restListFillerhazardsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFillerhazardsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = fillerhazardPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Fillerhazard> fillerhazards = fillerhazardDAO.findAllFillerhazards(startResult,
				cmiPagination.getPaginationSize());
		String fillerhazardString = cmiPsonService.toPsonString(fillerhazards, 2, cmiPagination);

		return JSONObject.parse(fillerhazardString);
	}

	@RequestMapping("/fillerhazardSelectBox")
	@ResponseBody
	public JSONObject fillerhazardSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Filler":
				entitySet = fillerService.loadFillersByIdSet(searchValue);
				break;
			case "Hazard":
				entitySet = hazardService.loadHazardsByIdSet(searchValue);
				break;

			// 被引用键
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Filler":
				entitySet = fillerDAO.findAllFillers((pageNumber - 1) * paginationSize, paginationSize);
				count = fillerService.countFillers();
				break;
			case "Hazard":
				entitySet = hazardDAO.findAllHazards((pageNumber - 1) * paginationSize, paginationSize);
				count = hazardService.countHazards();
				break;

			// 被引用键
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Filler":
				entitySet = fillerDAO.findFillerByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = fillerService.countFillersByName(queryword);
				break;
			case "Hazard":
				entitySet = hazardDAO.findHazardByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = hazardService.countHazardsByName(queryword);
				break;

			// 被引用键
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
